package com.shopcart.controller;


import com.shopcart.pojo.ShoppingCart;
import com.shopcart.service.ShoppingCartService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shopping-cart")
public class ShoppingCartController {

    private final ShoppingCartService shoppingCartService;

    public ShoppingCartController(ShoppingCartService shoppingCartService) {
        this.shoppingCartService = shoppingCartService;
    }

    // 添加商品到购物车
    @PostMapping
    public ResponseEntity<ShoppingCart> addToCart(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart addedCartItem = shoppingCartService.addToCart(shoppingCart);
        return new ResponseEntity<>(addedCartItem, HttpStatus.CREATED);
    }

    // 更新购物车商品信息（如数量等）
    @PutMapping
    public ResponseEntity<ShoppingCart> updateCartItem(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart updatedCartItem = shoppingCartService.updateCartItem(shoppingCart);
        return new ResponseEntity<>(updatedCartItem, HttpStatus.OK);
    }

    // 删除购物车商品项
    @DeleteMapping("/{cartId}")
    public ResponseEntity<Void> deleteCartItem(@PathVariable String cartId) {
        shoppingCartService.deleteCartItem(cartId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    // 根据用户ID获取购物车商品列表
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<ShoppingCart>> listCartItemsByUserId(@PathVariable String userId) {
        List<ShoppingCart> cartItems = shoppingCartService.listCartItemsByUserId(userId);
        return new ResponseEntity<>(cartItems, HttpStatus.OK);
    }

    // 根据购物车商品项ID获取详情
    @GetMapping("/{cartId}")
    public ResponseEntity<ShoppingCart> getCartItemById(@PathVariable String cartId) {
        ShoppingCart cartItem = shoppingCartService.getCartItemById(cartId);
        if (cartItem!= null) {
            return new ResponseEntity<>(cartItem, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}